package com.qingyun.web.controller.common;

import cn.hutool.core.util.RandomUtil;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.redis.RedisCache;
import com.qingyun.common.utils.StringUtils;
import com.qingyun.framework.web.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Classname SmsCommonController
 * @Author dyh
 * @Date 2021/9/17 9:18
 */
@RestController
@RequestMapping("/Sms")
@AllArgsConstructor
@Api(value = "短信服务",tags = "短信服务")
public class SmsCommonController {

	private SmsService smsService;

	private RedisCache redisCache;

	@ApiOperation("微信小程序发送手机验证码")
	@PostMapping("getLoginCatcha")
	public AjaxResult sendCaptchaSms(@RequestBody Map<String, String> map) throws Exception {
		String succCode = redisCache.getCacheObject(map.get("phone"));
		if (StringUtils.isNotBlank(succCode)) {
			return AjaxResult.error("请稍后再获取");
		}
		int[] ints = RandomUtil.randomInts(6);
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < ints.length; i++) {
			builder.append(ints[i]);
		}
		Boolean smsCode = smsService.sendSms(map.get("phone"), builder.toString());
		if(!smsCode){
			return AjaxResult.error("发送失败,请联系系统管理员");
		}
		redisCache.setCacheObject(map.get("phone"), builder.toString(), 1, TimeUnit.MINUTES);
		return AjaxResult.success(builder.toString());
	}

}
